
package com.zsrt.xml.dao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.zsrt.xml.studententity.StudentEntity;

public class StudentDaoImpl implements StudentDao{

	/*@Override
	public void listNodes(Element node) {

		System.out.println("当前节点的名称：：" + node.getName());  
        // 获取当前节点的所有属性节点  
        List<Attribute> list = node.attributes();  
        // 遍历属性节点  
        for (Attribute attr : list) {  
            System.out.println(attr.getText() + "-----" + attr.getName()  
                    + "---" + attr.getValue());  
        }  
  
        if (!(node.getTextTrim().equals(""))) {  
            System.out.println("文本内容：：：：" + node.getText());  
        }  
  
        // 当前节点下面子节点迭代器  
        Iterator<Element> it = node.elementIterator();  
        // 遍历  
        while (it.hasNext()) {  
            // 获取某个子节点对象  
            Element e = it.next();  
            // 对子节点进行遍历  
            listNodes(e); 
            
        }  
    }  */
	
	/**
	 * 遍历节点
	 */
	 @SuppressWarnings("rawtypes")
	public List<StudentEntity> listNodes(Element node) {  
		 List<StudentEntity> studentList = new ArrayList<StudentEntity>();
		 //遍历所有节点
		 for(Iterator it=node.elementIterator();it.hasNext();){
			 
            Element element = (Element) it.next();        
           // do something   
            Element stu = element.element("name");
            Element stuNum = element.element("id");
            Element stuAge = element.element("age");
            Element stuSex = element.element("sex");
            
            //得到一个学生的属性
            StudentEntity student01 = new StudentEntity(stuNum.getText(),stu.getText(),stuSex.getText(),Integer.parseInt(stuAge.getText()));
            studentList.add(student01);
		 }        
        return studentList;
    }

	@Override
	public boolean addStudent(Document document) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入你想添加的学生个数：");
        int j = scanner.nextInt();
		for(int i=0;i<j;i++){
			
			//Element node = document.getRootElement();  
			System.out.println("请输入添加的学生学号");
			String idNum = scanner.next();
			System.out.println("请输入添加的学生姓名");
			String name = scanner.next();
			System.out.println("请输入添加的学生性别");
			String sex = scanner.next();
			System.out.println("请输入添加的学生年龄");
			Integer age = scanner.nextInt();
			//StudentEntity arg0 = new StudentEntity(idNum, name, sex, age);
			
			Element root=document.getRootElement();
			//添加student节点
			Element stu = root.addElement("student");
			//添加student 下面的节点
			Element idEle = stu.addElement("stuNum");
			Element nameEle = stu.addElement("name");
			Element sexEle = stu.addElement("sex");
			Element ageEle = stu.addElement("age");
			
			//赋值
			idEle.setText(idNum);
			nameEle.setText(name);
			sexEle.setText(sex);
			ageEle.setText(String.valueOf(age));
			
			fileClose(document);
			System.out.println("添加成功");  		
		}
        scanner.close();
		return true;
	}

	@Override
	public boolean deleteStudent(Document document,String id) {

		//获取根节点
		Element root = document.getRootElement();
		//获取id节点的集合
		/*List<Element> lists = root.elements("stuNum");
		for(Element e:lists){
			String num = e.getText();
			if(num.equals(id)){
				Element parent = e.getParent();
				boolean b = root.remove(parent);
				System.out.println("1");
			}
		}*/
		
		if(root==null){
			System.out.println("该xml表是空的");
			return false;
		}else{
			
			for(@SuppressWarnings("rawtypes")
			Iterator it=root.elementIterator();it.hasNext();){
				Element element = (Element) it.next();  
				
				String num = element.elementText("stuNum");
				if(num.equals(id)){
					element.getParent().remove(element);
					System.out.println("删除成功");
					//重新写入到XML文档
					fileClose(document);		
					
					return true;
				}
			}
		}
		System.out.println("未找到该学生");
		return false;
	}

	private void fileClose(Document document) {
		OutputFormat of = OutputFormat.createPrettyPrint();
		of.setEncoding("UTF-8");
		XMLWriter xw = null;
		try {
			File file = new File("src/com/zsrt/xml/student.xml");
			xw = new XMLWriter(new FileOutputStream(file ),of);
			xw.write(document);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(xw !=null){
				
				try {
					xw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean updateStudent(Document document, String id) {

		Scanner scanner = new Scanner(System.in);
		//获取根节点
		Element root = document.getRootElement();
		for(Iterator it=root.elementIterator();it.hasNext();){
			Element element = (Element) it.next();  
			
			String num = element.elementText("stuNum");
			if(num.equals(id)){
				System.out.println("请输入你想修改的年龄;");
				int age =scanner.nextInt() ;
				
				element.element("age").setText(String.valueOf(age));
				
				System.out.println("请输入你想修改的姓名;");
				String  name =scanner.next() ;
				element.element("name").setText(name);
				System.out.println("请输入你想修改的性别;");
				String  sex =scanner.next() ;
				element.element("sex").setText(sex);
				System.out.println("修改成功");
				scanner.close();
				fileClose(document);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean deleteStudent(Document document, String[] ids) {
		
		Element root = document.getRootElement();
		for(@SuppressWarnings("rawtypes")
		Iterator it=root.elementIterator();it.hasNext();){
			Element element = (Element) it.next();  
			
			String num = element.elementText("stuNum");
			for(int index=0;index<ids.length;index++){
				
				if(num.equals(ids[index])){
					element.getParent().remove(element);
					System.out.println("删除成功");
				}
			}
		}
		fileClose(document);
		return true;
	}  
	
}
